package com.ruoyi.warning.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.hik.EventLogData;
import com.ruoyi.common.hik.Events;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.warning.domain.entity.Configuration;
import com.ruoyi.warning.domain.entity.Device;
import com.ruoyi.warning.domain.entity.Event;
import com.ruoyi.warning.domain.query.EventQuery;
import com.ruoyi.warning.domain.vo.EventVO;
import com.ruoyi.warning.domain.vo.WarningConfigurationRuleRelationVO;
import com.ruoyi.warning.mapper.EventMapper;
import com.ruoyi.warning.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 告警模版表 服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-02-20
 */
@Service
public class EventServiceImpl extends ServiceImpl<EventMapper, Event> implements IEventService {
    @Resource
    private HikApiService hikApiService;
    @Resource
    private IDevicesService devicesService;
    @Resource
    private IConfigurationService configurationService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Resource
    private EventMapper EventMapper;
    @Resource
    private IWarningConfigurationRuleRelationService relationService;
    @Override
    public TableDataInfo getEventPage(EventQuery query) {
        Page<Event> page = PageHelper.startPage(query.getPageNum(),query.getPageSize());
        List<EventVO> list = EventMapper.getEventList(query);
        return new TableDataInfo(list, page.getTotal());
    }

    @Override
    public List<Event> getEventList(EventQuery query) {
        LambdaQueryWrapper<Event> wrapper = new QueryWrapper<Event>().lambda()
                .eq(query.getEventLevel()!=null,Event::getEventLevel,query.getEventLevel())
                .ge(query.getStartTime()!=null,Event::getWarningTime,query.getStartTime())
                .le(query.getEndTime()!=null,Event::getWarningTime,query.getEndTime())
                .like(query.getResName()!=null,Event::getDeviceName,query.getResName())
                .eq(query.getRegionIndexCode()!=null,Event::getRegionIndexCode,query.getRegionIndexCode())
                .eq(query.getCameraIndexCode()!=null,Event::getDeviceId,query.getCameraIndexCode());
        return this.list(wrapper);
    }

    @Override
    public String pictureUrl(String id) {
        return null;
    }

    @Override
    public void video(String id, HttpServletResponse response) {

    }
    // 下载文件
    public String download(Event event) {
        return null;
    }

    @Override
    public void receiveEvent(Object obj) throws Exception {
        java.util.Map<String, Object> map = com.alibaba.fastjson.JSON.parseObject(com.alibaba.fastjson.JSON.toJSONString(obj), java.util.Map.class);

        System.out.println("------------------------");
        System.out.println("接收事件");
        System.out.println(map);
        System.out.println("------------------------");

        Event event = new Event();
        Device device =
                devicesService.getOne(
                        new QueryWrapper<Device>().lambda()
                                .eq(Device::getHostname,map.get("hostname").toString()));
        event.setDeviceId(device.getDeviceId());
        event.setHostName(map.get("hostname").toString());
        event.setDeviceName(map.get("sysname").toString());
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        java.time.LocalDateTime warningTime = java.time.LocalDateTime.parse(map.get("timestamp").toString(), formatter);
        event.setWarningTime(warningTime);
        if(map.get("title").toString().contains("-")){
            event.setTitle(map.get("title").toString().split(" - ")[1]);
        }else {
            event.setTitle(map.get("title").toString());
        }

        event.setMsg(map.get("msg").toString());
        event.setRemark("正在告警中");
        this.saveOrUpdate(event);
        LambdaQueryWrapper<Configuration> configurationwrapper = new QueryWrapper<Configuration>().lambda()
                .like(Configuration::getDeviceId,event.getDeviceId())
//                .like(Configuration::getMonth, LocalDate.now().format(DateTimeFormatter.ofPattern("MM")))
                // 按照创建时间降序排序
                .eq(Configuration::getDelFlag,0)
                .orderByDesc(Configuration::getCreateTime)
//                .last("LIMIT 1")
                ;

        List<Configuration> list = configurationService.list(configurationwrapper);
        if(ObjectUtils.isEmpty(list)){
            event.setRemark("告警方式未配置");
            this.saveOrUpdate(event);
            return;
        }
        Event finalEvent = event;
        for(Configuration configuration:list){
            List<WarningConfigurationRuleRelationVO> relationList = relationService.getRuleRelationList(configuration.getId());
            if(relationList.stream()
                    .anyMatch(relation -> finalEvent.getTitle().equals(relation.getRuleName()))){
//                event = configurationService.warningSend(event,configuration);
                event.setRemark("告警通知中。。。");
                break;
            }else {
                event.setRemark("告警方式未配置对应规则");
            }
        }
        this.saveOrUpdate(event);
    }

    @Override
//    @Scheduled(fixedRate = 1 * 60 * 1000) // 每 1 分钟执行一次
    public String refresh() throws Exception {
        List<SysDictData> list = sysDictDataMapper.selectDictDataByType("hik_setting")   ;
//        Map<String, String> resultMap = list.stream()
//                .collect(Collectors.toMap(
//                        item -> item.getDictLabel(),
//                        item -> item.getDictValue()
//                ));

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        OffsetDateTime currentOffsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
//        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSXXX");
//        String currentTime = currentOffsetDateTime.format(formatter);

        // 获取1分钟前的时间
        LocalDateTime oneMinutesAgo = now.minus(1, ChronoUnit.MINUTES);
        OffsetDateTime oneMinutesAgoOffsetDateTime = oneMinutesAgo.atOffset(ZoneOffset.ofHours(8));
        String oneMinutesAgoTime = oneMinutesAgoOffsetDateTime.format(formatter);

        // 获取2分钟前的时间
        LocalDateTime twoMinutesAgo = now.minus(2, ChronoUnit.MINUTES);
        OffsetDateTime twoMinutesAgoOffsetDateTime = twoMinutesAgo.atOffset(ZoneOffset.ofHours(8));
        String twoMinutesAgoTime = twoMinutesAgoOffsetDateTime.format(formatter);

//        fiveMinutesAgoTime = "2025-03-01T00:00:38.154+08:00";
//        currentTime = "2025-03-11T00:00:38.154+08:00";

//        fiveMinutesAgoTime = "2025-03-14T17:11:00.14+08:00";
//        currentTime = "2025-03-14T17:12:00.14+08:00";
        System.out.println("===================================");
        System.out.println(twoMinutesAgoTime);
        System.out.println(oneMinutesAgoTime);
        System.out.println("===================================");
        // 查询1分钟内的事件
        List<Events> eventsList = hikApiService.searchEvents(twoMinutesAgoTime,oneMinutesAgoTime,"100","1");
        List<Event> eventList = new ArrayList<>();
        if(ObjectUtils.isEmpty(eventsList)){
            return null;
        }
        for(Events events:eventsList){
            Event event=new Event();
            BeanUtils.copyProperties(events.getEventLogSrcList().get(0),event);
            BeanUtils.copyProperties(events,event);
            event.setWarningTime(events.getStartTime().toLocalDateTime());

            eventList.add(event);
        }

        //找到对应的配置，进行报警
        for(Event event:eventList){
            LambdaQueryWrapper wrapper = new QueryWrapper<Event>().lambda()
                    .eq(Event::getDeviceId,event.getDeviceId())
                    .eq(Event::getIsWarning,1)
                    .orderByDesc(Event::getWarningTime)
                    .last("limit 1");
            Event event1 = this.getOne(wrapper);
            LambdaQueryWrapper<Configuration> configurationwrapper = new QueryWrapper<Configuration>().lambda()
                    .like(Configuration::getDeviceId,event.getDeviceId())
                    .like(Configuration::getMonth, LocalDate.now().format(DateTimeFormatter.ofPattern("MM")))
                    // 按照创建时间降序排序
                    .orderByDesc(Configuration::getCreateTime)
                    .last("LIMIT 1");
            Configuration configuration = configurationService.getOne(configurationwrapper);
            this.saveOrUpdate(event);
            if(ObjectUtils.isEmpty(configuration)){
                event.setRemark("配置为空");
                this.saveOrUpdate(event);
                continue;
            }
            if(ObjectUtils.isEmpty(event1)){
//                configurationService.warningSend(event,configuration);
                continue;
            }
            Duration duration = Duration.between(event1.getWarningTime(), event.getWarningTime());
            System.out.println("===================================");
            System.out.println(event.getWarningTime());
            System.out.println(event1.getWarningTime());
            System.out.println(duration.toMinutes());
            System.out.println("===================================");
            long minutes = Math.abs(duration.toMinutes());
            //超过设定时间以上的判定为新的事件
            if(minutes>configuration.getTimeInterval()){
//                configurationService.warningSend(event,configuration);
            }else {
                event.setRemark("时间间隔小于"+configuration.getTimeInterval()+"分钟");
                this.saveOrUpdate(event);
            }
        }

        return null;
    }

//    public String refresh() throws Exception {
//        try {
//            Loader.load(avutil.class); // 尝试加载核心类
//            System.out.println("FFmpeg 库加载成功！");
//        } catch (UnsatisfiedLinkError e) {
//            System.err.println("FFmpeg 库加载失败：" + e.getMessage());
//        }
//        return null;
//    }


    public static void main(String[] args) {
        String a = "{\"channelID\":34,\"channelName\":\"铁路维修站集中充电点热成像\",\"dataProcInterval\":\"30\",\"dataType\":\"thermalImaging\",\"dateTime\":\"2025-03-07T07:16:15.183+08:00\",\"eventDescription\":\"thermometry\",\"eventType\":\"thermometry\",\"ipAddress\":\"169.169.129.77\",\"picUploadInterval\":\"25\",\"portNo\":8000,\"recvTime\":\"2025-03-07T07:16:15.183+08:00\",\"sendTime\":\"2025-03-07T07:16:15.213+08:00\",\"thermometry\":[{\"alarmFilterTime\":0,\"alarmLevel\":1,\"alarmRule\":0,\"alarmType\":0,\"alertFilterTime\":0,\"curTemperature\":\"212.2\",\"imageUrl\":\"http://169.169.128.66:6120/pic?6d00=3802l18-do6518*31e337a6-48d0679ba*811s=**813==tp*7313=1942105*7189=6l8o1*23e-=847ec3pi174o=0-3f0040\",\"point\":[{\"x\":\"0\",\"y\":\"0\"},{\"x\":\"0\",\"y\":\"1\"},{\"x\":\"1\",\"y\":\"1\"},{\"x\":\"1\",\"y\":\"0\"}],\"presetNo\":0,\"ptzInfo\":{\"focus\":0,\"pan\":\"0\",\"tilt\":\"0\",\"zoom\":\"0\"},\"ruleCalibType\":1,\"ruleId\":0,\"ruleTemperature\":\"200\",\"targetAttrs\":{\"cameraIndexCode\":\"7c17be2f54c94fddb987e4894bc49b7a\",\"deviceIndexCode\":\"e3eb81ac30d04a668357f1a1813c07c7\",\"imageServerCode\":\"0c9380ec-f6f1-4e97-8fea-f0f9e23af7c0\",\"picServerIndexCode\":\"0c9380ec-f6f1-4e97-8fea-f0f9e23af7c0\"},\"thermometryUnit\":0,\"toleranceTemperature\":\"3\",\"visiblePicUrl\":\"http://169.169.128.66:6120/pic?0df300=4470ip-ceo161-e22*7o8=2840*4l2=0927350724t1=314**ps==818b*=6118*a69730d14-8a893e-5*l158od08162=003\"}]}";
        EventLogData eventLogData = JSON.parseObject(a, EventLogData.class);
        System.out.println(eventLogData);
    }
}
